$(function(){
	var socket = io.connect(url)
		// , reset = io.connect(url + '/reset')
		, $buttons = $("#emp_list button");

	$buttons.click(buttonClickHandler);

	function buttonClickHandler(e){
		if($(this).hasClass("btn-default")){
			socket.emit("do_emit", { event:'select', id: $(this).data("roster-id") });

			setButtonState($(this));
		}
		else
			e.preventDefault();
	}

	$("#resetBtn").click(function(){
		if($(this).hasClass("editing")){
			$(".is-present").prop("checked", true);
		}
		else{
			socket.emit("do_emit", { event:'reset', list: empList });
			fullRefresh();
		}
	});

	$("#settingBtn").click(function(){
		if($(this).hasClass("editing")){
			$("#emp_list").show();
			$("#emp_settings").hide();
			$(this).removeClass("editing")
				.find("span").text("Settings");

			saveSettings();
			$("#resetBtn").removeClass("editing");
		}
		else{
			$("#emp_list").hide();
			$("#emp_settings").show();

			$(this).addClass("editing")
				.find("span").text("Save");

			$("#resetBtn").addClass("editing");
		}
	});

	socket.on('update', function (data) {
		switch(data.event){
			case 'single_update': 
  			singleUpdate(data.data.id);
  			break;
  		case 'full_refresh':
  			fullRefresh();
  			break;
  		case 'refresh_present':
  			refresh_present(data.data);
  			break;
		}
	  
	});

	function singleUpdate(id){
		var btn = $("#emp_"+id);

	  setButtonState(btn);
	}

	function fullRefresh(){
		$("#emp_list .btn-success").addClass("btn-default").removeClass("active btn-success")
			.find("i.glyphicon").removeClass("glyphicon-refresh spinner glyphicon-ok-circle").addClass("glyphicon-record");
	}

	
	function refresh_present(data){
		var list = data;

		for(var i=0; i<list.length; i++){
			var $empBtn = $("#emp_"+list[i].id);
			if(!list[i].isPresent){
				$empBtn.removeClass("btn-default").addClass("btn-warning")
					.find(".glyphicon").removeClass("glyphicon-refresh spinner glyphicon-ok-circle glyphicon-record").addClass("glyphicon-remove-circle");
			}
			else{
				if($empBtn.hasClass("btn-warning")){
					$empBtn.addClass("btn-default").removeClass("btn-warning")
						.find("i.glyphicon").removeClass("glyphicon-remove-circle").addClass("glyphicon-record");
				}
			}
		}
	}

	function saveSettings(){
		var empListPresent = [];
		$(".is-present").each(function(){
			empListPresent.push({id:$(this).data("roster-id"), isPresent: $(this).is(":checked")});

		});
		socket.emit("do_emit", { event:'save', list: empListPresent });
		refresh_present(empListPresent);
	}

	function setButtonState(btn) {
		$(".btn-success").removeClass("active");
	  $(".glyphicon-refresh.spinner").removeClass("glyphicon-refresh spinner").addClass("glyphicon-ok-circle");

	  btn.removeClass("btn-default").addClass("btn-success active")
	  	.find("i").removeClass("glyphicon-record glyphicon-ok-circle").addClass("glyphicon-refresh spinner");
	}
});